package com.QK.cnstudy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.QK.cnstudy.adapter.WorkAdapter;
import com.QK.cnstudy.db.DBManager;
import com.QK.cnstudy.entity.Work;

public class WorkSelectActivity extends Activity implements OnItemClickListener, OnClickListener {

    private int termId = 1;
    private int textbookId = 1;
    private DBManager dbManager;

    private ListView listView;
    private WorkAdapter adapter;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    Button backButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.work_select);
        dbManager = CnStudyApp.app.dbManager;

        Bundle bundle = getIntent().getExtras();
        termId = (Integer) bundle.get("term_id");
        textbookId = (Integer) bundle.get("textbook_id");
        getView();
        setListViewData();
        adapter = new WorkAdapter(this, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        backButton.setOnClickListener(this);
    }

    public void setListViewData() {
        List<Work> works = dbManager.getWorksByTextbookAndTerm(textbookId, termId);
        for (Work work : works) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("object", work);
            list.add(map);
        }
    }

    public void getView() {
        listView = (ListView) findViewById(R.id.work_list);
        backButton = (Button) findViewById(R.id.back);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

        Work work = (Work) list.get(arg2).get("object");
        Intent intent = new Intent(this, StudyGroup_Activity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putInt("id", work.getId());
        intent.putExtras(bundle);
        startActivity(intent);
        dbManager.setCurStudyWorkId(work.getId());
        work.updateWorkRecord(dbManager.getSqLiteDatabase());
        CnStudyApp.app.workId = work.getId();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.back:

            onBackPressed();
            break;

        default:
            break;
        }

    }
}
